package com.icesoft.base.manager.security.login.handle;

import com.icesoft.base.manager.helper.AuthUser;
import com.icesoft.base.manager.security.config.LoginPropertySetting;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.web.helper.ResponseUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
@AllArgsConstructor
public class UnifiedAuthSuccessHandler implements AuthenticationSuccessHandler {
    private static final String PRINCIPAL_NAME_INDEX_NAME = "org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME";
    private LoginPropertySetting loginPropertySetting;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) {
        AuthUser user = (AuthUser) authentication.getPrincipal();
        if (log.isDebugEnabled()) {
            log.debug("{}登录成功，请求权限：{}", user.getUsername(), authentication.getAuthorities());
        }
        WebUtils.setSessionAttribute(request, PRINCIPAL_NAME_INDEX_NAME, user.getUsername());
        ResponseUtils.writeJson(response, Resp.success(loginPropertySetting.getSuccessUrl()));

    }

}
